'use client';

import { useState } from 'react';
import { useSession } from 'next-auth/react';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';

// 删除 @prisma/client 的导入，直接定义类型
type CommentWithUser = {
  id: string;
  content: string;
  tripId: string;
  userId: string;
  createdAt: Date;
  updatedAt: Date;
  user: {
    id: string;
    name: string | null;
  };
};

export function CommentSection({
  tripId,
  initialComments,
}: {
  tripId: string;
  initialComments: CommentWithUser[];
}) {
  const { data: session, status } = useSession();
  const [comments, setComments] = useState(initialComments);
  const [content, setContent] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!session?.user?.id) return;

    setIsSubmitting(true);
    setError(null);
    try {
      const response = await fetch(`/api/trips/${tripId}/comments`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ content }),
      });

      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || '评论失败');
      }

      setComments([data, ...comments]);
      setContent('');
    } catch (error) {
      console.error('Comment error:', error);
      setError(error instanceof Error ? error.message : '评论失败');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="mt-8">
      <h2 className="text-lg font-semibold text-gray-900 mb-4">评论</h2>
      
      {session ? (
        <form onSubmit={handleSubmit} className="mb-6">
          <textarea
            value={content}
            onChange={(e) => setContent(e.target.value)}
            placeholder="写下你的评论..."
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            rows={3}
          />
          <button
            type="submit"
            disabled={isSubmitting || !content.trim()}
            className="mt-2 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
          >
            发表评论
          </button>
        </form>
      ) : (
        <p className="text-gray-500 mb-6">请登录后发表评论</p>
      )}

      <div className="space-y-4">
        {comments.map((comment) => (
          <div key={comment.id} className="bg-gray-50 rounded-lg p-4">
            <div className="flex justify-between items-start">
              <span className="font-medium text-gray-900">
                {comment.user.name || '匿名用户'}
              </span>
              <span className="text-sm text-gray-500">
                {format(comment.createdAt, 'yyyy年MM月dd日 HH:mm', { locale: zhCN })}
              </span>
            </div>
            <p className="mt-2 text-gray-600">{comment.content}</p>
          </div>
        ))}
      </div>
    </div>
  );
} 